package org.example.config.filters;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.example.model.user.dtos.UserIdentityDto;
import org.example.utils.JwtUtils;
import org.example.utils.UserIdThreadLocalUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt过滤器
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class JWTFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //请求对象和响应对象
        HttpServletRequest request = ((HttpServletRequest) servletRequest);
        HttpServletResponse response = ((HttpServletResponse) servletResponse);

        //获取请求url
        String requestUrl = request.getRequestURL().toString();
        log.info(requestUrl);

        //不需要token就可以访问的接口列表
        String[] urlList = new String[] {
                "/login",
                "/register",
                "/swagger",
                "/css",
                "/js",
                "/index.html",
                "favicon.ico",
                "/doc.html",
                "/webjars",
                "/csrf",
                "/v2/api-docs",
        };

        for (String url : urlList) {
            if (requestUrl.contains(url)) {
                if (request.getMethod().equals("GET") || request.getMethod().equals("POST")) {
                    filterChain.doFilter(request, response);
                    return;
                }
            }
        }

        if (request.getMethod().equals("OPTIONS")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 获取请求对象中的token
        String token = request.getHeader("Authorization");
        token = token.substring(7);

        //如何toke为空
        if (StringUtils.isBlank(token)) {
            return;
        }

        //检查token是否合法
        try {
            JwtUtils.Verify(token);
        } catch (Exception e) {
            return;
        }

        //获取token中包含的信息，并放行
        String userInfo = JwtUtils.GetInfoFromToken(token);
        UserIdentityDto userIdentityDto = JSON.parseObject(userInfo, UserIdentityDto.class);
        UserIdThreadLocalUtils.setUser(userIdentityDto);
        filterChain.doFilter(request, response);
    }
}

